package com.servlet;

import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.DBUtils.DBUtil;
import com.dao.AccountDao;
import com.dao.TopicDao;
import com.mode.BBSAccount;
import com.mode.BBSTopic;

/**
 * Servlet implementation class HomePageServlet
 */
@WebServlet("/HomePageServlet")
public class HomePageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HomePageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("UTF-8");
		response.setCharacterEncoding("UTF-8");
		Writer out=response.getWriter();
		
		BBSAccount ab=new BBSAccount();
		AccountDao ad=new AccountDao();
		List<BBSAccount> lisa=ad.find(ab);
		
		Connection con=DBUtil.getconn();
		String sql="select * from bbstopic limit 0,30";
		
		try {
			Statement stm = con.createStatement();
			ResultSet rs=stm.executeQuery(sql);
			String st="[";
			while(rs.next()){
				String name="";
				for (BBSAccount b : lisa) {
					if(b.getAccountId()==rs.getInt("FK_a")){
						name+=b.getNickName();
						break;
					}
				}
				st+="{\"id\":"+rs.getInt("topicID")+","+"\"title\":\""+rs.getString("title")+"\","+"\"nickName\":\""+name+"\"},";
			}
			String stt=st.substring(0, st.length()-1);
			stt+="]";
//			System.out.println(stt);
			out.write(stt);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
